// pages/typeManage/index.js
const app = getApp();
Page({

    /**
     * 页面的初始数据
     */
    data: {
        dictValue: '',
        addShow: false,
        updateObj: {},
        type: 1,
        status: '',
        oprateUrl: '',
        listUrl: '',
        list: [
            { name: '打包', status: 0, classifyList: [], listUrl: '/api/category/selPackList', addUrl: '/api/category/savePack', updateUrl: '/api/category/updatePack', delUrl: '/api/category/delPack' },
            { name: '品牌', status: 1, classifyList: [], listUrl: '/api/category/selBrandList', addUrl: '/api/category/saveBrand', updateUrl: '/api/category/updateBrand', delUrl: '/api/category/delBrand' },
            { name: '型号', status: 2, classifyList: [], listUrl: '/api/category/selMaterialList', addUrl: '/api/category/saveMaterial', updateUrl: '/api/category/updateMaterial', delUrl: '/api/category/delMaterial' },
            { name: '壁厚', status: 3, classifyList: [], listUrl: '/api/category/selThicknessList', addUrl: '/api/category/saveThickness', updateUrl: '/api/category/updateThickness', delUrl: '/api/category/delThickness' },
            { name: '开启', status: 4, classifyList: [], listUrl: '/api/category/selOpenList', addUrl: '/api/category/saveOpen', updateUrl: '/api/category/updateOpen', delUrl: '/api/category/delOpen' },
        ],
        activeNames: [],
        admin: 0
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        wx.hideShareMenu();
        this.setData({ 
          admin: wx.getStorageSync('admin')
        });
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {
      this.data.list.forEach(item => {
        this.getList(item.listUrl, item.status); // 品牌
      });
    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {

    },

    getList(url, status) {
        wx.showLoading();
        wx.request({
            url: `${app.globalData.baseUrl}${url}`,
            method: "GET",
            header: {
                'token': wx.getStorageSync('token'),
                "Content-Type": "application/json"
            },
            success: (res) => {
                wx.hideLoading();
                if (res.data.code == 0) {
                    const list = JSON.parse(JSON.stringify(this.data.list));
                    const arr = res.data.rows;
                    arr.forEach((item,index) => {
                        item.index = arr?.length - index;
                      if(status == 2) {
                        item.dictCode = item.materialId;
                        item.dictValue = item.materialName;
                      }else {
                        item.dictCode = item.id;
                        item.dictValue = item.name;
                      }
                    });
                    list.forEach(item => {
                        if (item.status == status) {
                            item.classifyList = res.data.rows
                        }
                    })
                    this.setData({ list });
                } else {
                    wx.showToast({
                        title: res.data.msg || '出错啦！',
                        icon: 'error',
                        duration: 2000
                    })
                }
            }
        })
    },

    add(e) {
      this.setData({ addShow: true, type: 1, status: e.currentTarget.dataset.status, oprateUrl: e.currentTarget.dataset.url, listUrl: e.currentTarget.dataset.listurl });
    },
    update(e) {
        this.setData({
            addShow: true,
            type: 2,
            updateObj: e.currentTarget.dataset,
            dictValue: e.currentTarget.dataset.dictvalue,
            status: e.currentTarget.dataset.status,
            oprateUrl: e.currentTarget.dataset.url,
            listUrl: e.currentTarget.dataset.listurl
        });
    },
    delete(e) {
        const id = e.currentTarget.dataset.code;
        const status = e.currentTarget.dataset.status;
        const url = e.currentTarget.dataset.url;
        const listurl = e.currentTarget.dataset.listurl;
        let parmas = `?id=${id}`;
        if(status == 2) parmas = `?materialId=${id}`
        const that = this;
        wx.showModal({
            content: '确认删除吗？',
            success: function (sm) {
                if (sm.confirm) {
                    wx.request({
                        url: `${app.globalData.baseUrl}${url}${parmas}`,
                        method: "GET",
                        header: {
                            'token': wx.getStorageSync('token'),
                            "Content-Type": "application/json"
                        },
                        success: (res) => {
                            if (res.data.code == 0) {
                                that.getList(listurl, status);
                                wx.showToast({
                                    title: '成功删除',
                                });
                            } else {
                                wx.showToast({
                                    title: res.data.msg || '报错啦！',
                                    duration: 2000
                                })
                            }
                        }
                    })
                } else {
                    console.log('用户点击取消');
                }
            }
        })
    },
    onDictValueChange(e) {
        this.setData({ dictValue: e.detail });
    },
    onDictValueHidden() {
        this.setData({ addShow: false, dictValue: '' });
    },
    addDictValue() {
        wx.showLoading();
        if (!this.data.dictValue) {
            wx.showToast({
                title: `请填写名称`,
                icon: 'error',
            })
            return;
        }
        let data = { name: this.data.dictValue }
        if(this.data.status == 2) {
          data = { materialName: this.data.dictValue }
        }
        if (this.data.type == 2) {
          if(this.data.status == 2) data.materialId = this.data.updateObj.dictcode;
          else data.id = this.data.updateObj.dictcode;
        }
        wx.request({
            url: `${app.globalData.baseUrl}${this.data.oprateUrl}`,
            method: "POST",
            data: data,
            header: {
                "Content-Type": "application/json",
                'token': wx.getStorageSync('token'),
            },
            success: (res) => {
                wx.hideLoading();
                if (res.data.code == 0) {
                    wx.showToast({
                        title: '操作成功',
                    });
                    this.getList( this.data.listUrl, this.data.status);
                    this.onDictValueHidden();
                } else if (res.data.code == 500) {
                    wx.showToast({
                        title: res.data.msg || '报错啦！',
                        icon: 'error',
                        duration: 2000
                    })
                } else {
                    wx.showToast({
                        title: '系统错误，请重新登录',
                    })
                }
            },
            fail: () => {
                wx.hideLoading();
                wx.showToast({
                    title: '系统错误',
                });
                _that.setData({ loading: false });
            }
        })
    },
    collapseChange(e) {
        this.setData({ activeNames: e.detail.slice(-1) })
      },
})